import React, { useState, } from 'react';
import {

  PlusOutlined
} from '@ant-design/icons';
import {Modal,Upload,Form, Button,Space, Input,Layout, ConfigProvider, Select, Collapse, message} from 'antd';
import axios from "axios";


const { Content} = Layout;
const {TextArea} = Input

const getBase64 = (file) =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });


  // 发布按钮
  const SubmitButton = ({ form }) => {
    const [submittable, setSubmittable] = React.useState(false);
    const values = Form.useWatch([], form);
    React.useEffect(() => {
      form
        .validateFields({
          validateOnly: true,
        })
        .then(
          () => {
            setSubmittable(true);
          },
          () => {
            setSubmittable(false);
          },
        );
    }, [values]);
    return (
      <Button style={{width:100}} type="primary" htmlType="submit" disabled={!submittable}>
        发布
      </Button>
    );
  };





const Publish = () => {
  //跳转到首页
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');
  const [fileList, setFileList] = useState([
   
  ]);
  const handleCancel = () => setPreviewOpen(false);
  // 实现预览的函数
  const handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    setPreviewImage(file.url || file.preview);
    setPreviewOpen(true);
    setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1));
  };

  const handleChange = ({ fileList: newFileList }) => {
    
    setFileList(newFileList)

  }

  const handleUpload = async (options) => {
    const { onSuccess, onError, file } = options;

    try {
      const formData = new FormData();
      formData.append("file", file);

      // 发送POST请求到后端API接口
      const response = await axios.post("https://run.mocky.io/v3/435e224c-44fb-4773-9faf-380c5e6a2188", formData);

      // 根据后端API的返回结果进行处理
      if (response.status === 200) {
        message.success("图片上传成功");
        onSuccess(response.data, file);
      } else {
        message.error("图片上传失败");
        onError("上传失败");
      }
    } catch (error) {
      console.error(error);
      message.error("图片上传失败");
      onError("上传失败");
    }
  };


  // 上传的样式
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div
        style={{
          marginTop: 8,
        }}
      >
        上传图片
      </div>
    </div>
  );


  const [form] = Form.useForm();


  return (
    // 主题颜色
    <ConfigProvider
    theme={{
      token: {
        // Seed Token，影响范围大
        colorPrimary: '#73d13d',
        borderRadius: 20,

        // 派生变量，影响范围小
        colorBgContainer: '#f6ffed',
      },
    }}
  >
    <Layout>

      {/* Header头部 */}
      <Layout>




        {/* 内容部分 */}
        <Content
          style={{
            margin: '20px 16px',
            padding: 24,
            minHeight:'92vh',
            background:'#ffffff',
            borderRadius:20,
            maxHeight:'92vh',
            overflow:'auto',
          }}
        >
          <Form form={form} 
              name="validateOnly" 
              layout="vertical" 
              autoComplete="off"
              >
                
            <div style={{display:'flex',justifyContent:'center', }}>
            <Form.Item
              name ='标签'
              label="标签："
              style={{width:200, 
                marginTop:20,
                marginRight: 280,
              }}
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Select>
                <Select.Option value='考研'> 考研 </Select.Option>
                <Select.Option value='考研1'> 考研1 </Select.Option>
                <Select.Option value='考研2'> 考研2 </Select.Option>
                <Select.Option value='考研3'> 考研3 </Select.Option>
                <Select.Option value='考研4'> 考研4 </Select.Option>
              </Select>
            </Form.Item>
            <Form.Item
              name="标题"
              label="标题"
              style={{width:200,marginTop:20}}

              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input />
            </Form.Item>
            </div>
            
            {/* 内容栏 */}
            <Form.Item name='内容'>
              <div style={{marginTop:10 ,display:'flex'}}>
                  <TextArea
                  style={{width:700, margin:'auto'}}
                    placeholder="输入内容"
                    autoSize={{ minRows: 4, maxRows: 6 }}
                  />
              </div>
              </Form.Item>
            
         
            <Form.Item name='图片'>
              <div style={{
                  width:700,
                  height:300,
                  background:'#f6ffed',
                  borderRadius:20,
                  margin:'auto',
                  display:'flex'}}>
                <div style={{margin:'auto'}}>

                {/* 图片上传 */}
                <Upload
                style={{margin:'auto'}}
                  customRequest={handleUpload}
                  listType="picture-card"
                  fileList={fileList}
                  onPreview={handlePreview}
                  onChange={handleChange}
                >
                  {fileList.length >= 8 ? null : uploadButton}
                </Upload>

                {/* 预览效果 */}
                <Modal open={previewOpen} title={previewTitle} footer={null} onCancel={handleCancel}>
                  <img
                    alt="example"
                    style={{
                      width: '100%',
                    }}
                    src={previewImage}
                  />
                </Modal>
                </div>
              </div>
         
              </Form.Item>

              

                <Form.Item>
                  <div style={{display:'flex'}} >
                   {/* <Switch style={{marginLeft:200,marginTop:40}} /> */}
                  <Space style={{margin:'auto'}}>
                    <SubmitButton form={form} />
                    <Button style={{width:100}} htmlType="reset">取消</Button>
                  </Space>
                  </div>
                </Form.Item>
          </Form>



{/*               
          <Card hoverable style={cardStyle} bodyStyle={{ padding: 0, overflow: 'hidden' }}>
            <Flex justify="space-between">
            
              <Flex vertical align="flex-end" justify="space-between" style={{ padding: 32 }}>
              <div>asdasd  </div>
              <div>asdasdsdikolajwsdolja od hnaosidj   </div>
              
                <Button type="primary" href="https://ant.design" target="_blank">
                  Get Started
                </Button>
              </Flex>
              <img
                alt="avatar"
                src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"
                style={imgStyle}
              />
            </Flex>
          </Card> */}

          


        </Content>

      </Layout>
    </Layout>
  </ConfigProvider>

  );
};


export default Publish